import 'dart:convert';
import 'dart:ffi';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:logging/logging.dart';

/// 企业微信机器人客户端（修正版）
class WeChatRobot {

   //String key='6072ed81-7294-48b5-a017-fc990e2ff40e';
  static final Logger _logger = Logger('WeChatRobot');
  String key='';
  WeChatRobot(String k){
    // 初始化日志
    Logger.root.level = Level.ALL;
    Logger.root.onRecord.listen((record) {
      print('${record.level.name}: ${record.time}: ${record.message}');
    });
    //获取key
    key=k;
    
  }

  /// 发送文本消息
  Future<bool> sendTextMessage(String content) async {
    final Map<String, dynamic> message = {
      "msgtype": "text",
      "text": {
        "content": content,
      },
    };
  try
  {
    final response = await http.post(
      Uri.parse('https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=${key}'),
      headers: {"Content-Type": "application/json"},
      body: jsonEncode(message),
    );

    if (response.statusCode == 200) {
      _logger.info("消息发送成功: ${response.body}");
      return true;
    } else {
      _logger.severe("消息发送失败: ${response.statusCode}, ${response.body}");
      return false;
    }
  }catch(e)
  {
    _logger.severe("消息发送失败: ${e}");
    return false;

  }

  }
  /// 上传文件到企业微信（返回media_id）
  Future<String> uploadFile(String filePath) async {
    final uploadUrl = Uri.parse(
      'https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key=$key&type=file'
    );

    final file = File(filePath);
    if (!await file.exists()) {
      throw Exception('文件不存在: $filePath');
    }

    final request = http.MultipartRequest('POST', uploadUrl)
      ..files.add(await http.MultipartFile.fromPath('media', filePath));

    try {
      final response = await request.send();
      final body = await response.stream.bytesToString();
      
      if (response.statusCode == 200) {
        return jsonDecode(body)['media_id'] as String;
      } else {
        throw Exception('上传失败: ${jsonDecode(body)['errmsg']}');
      }
    } catch (e) {
      throw Exception('上传请求异常: $e');
    }
  }

  /// 发送文件消息（使用类内webhookUrl）
  Future<bool> sendFile(String mediaId) async {
    try {
      final response = await http.post(
        Uri.parse('https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=${key}'),
        headers: {'Content-Type': 'application/json'},
        body: jsonEncode({
          "msgtype": "file",
          "file": {"media_id": mediaId}
        }),
      );
      
      return response.statusCode == 200 && 
             jsonDecode(response.body)['errcode'] == 0;
    } catch (e) {

      return false;
    }
  }
}